package com.mzj.eagle.jobs.heartbeat.listener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import com.mzj.eagle.jobs.heartbeat.receiver.HeartbeatReceiver;

@RefreshScope
@Configuration
@Component
public class HeartbeatListener {

	private static final Logger LOG = LoggerFactory.getLogger(HeartbeatListener.class);

	@Value("${scale.heartbeat.queue}")
	private String queueName;
	@Value("${scale.heartbeat.exchange}")
	private String exchangeName;
	@Value("${scale.heartbeat.routing.key}")
	private String routingKey;

	@Bean(name = "machineHeartBeatQueue")
	public Queue pointsQueue() {
		return new Queue(queueName, true);
	}

	@Bean(name = "machineHeartBeatExchangeName")
	public TopicExchange pointsExchange() {
		return new TopicExchange(exchangeName);
	}

	@Bean
	public Binding smsBinding(@Qualifier("machineHeartBeatQueue") Queue pointsQueue,
			@Qualifier("machineHeartBeatExchangeName") TopicExchange pointsExchange) {
		return BindingBuilder.bind(pointsQueue).to(pointsExchange).with(routingKey);
	}

	@Bean
	SimpleMessageListenerContainer heartbeatContainer(ConnectionFactory connectionFactory,
			@Qualifier("heartbeatReceiver") HeartbeatReceiver listenerAdapter) {
		SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
		container.setConnectionFactory(connectionFactory);
		container.setQueueNames(new String[] { queueName });
		container.setMessageListener(listenerAdapter);
		container.setAcknowledgeMode(AcknowledgeMode.MANUAL);

		LOG.info("MachineHeartBeat mq info, exchangeName={}, queueName={}, routingKey={}", exchangeName, queueName, routingKey);
		return container;
	}
}
